package com.cp.util;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * 整个系统采用 TransmittableThreadLocal作为线程级别的数据存储
 * -TransmittableThreadLocal对原生的ThreadLocal进行了扩展,提供了线程池子父线程的数据传递
 * - tag:表示表示一种场景, 如:token,gray
 * @see com.cp.util.SceneTag
 *
 * @author YangXiaoLong
 * 2022/11/3 22:42
 */
public class SystemThreadLocal {

    public static final int DEFAULT_SIZE = 10;
    public static final TransmittableThreadLocal<Map<String, Object>> SYS_THREAD_LOCAL = new TransmittableThreadLocal<>();

    /**
     * des:
     * 设置值
     *
     * @param tag 场景类型  token,灰度
     * @param val 值
     * @author YangXiaoLong
     * @date 2022/11/3 23:04
     */
    public static void set(String tag, Object val) {
        Map<String, Object> local = SYS_THREAD_LOCAL.get();
        if (local == null) {
            local = new HashMap<>(DEFAULT_SIZE);
        }
        local.put(tag, val);
        SYS_THREAD_LOCAL.set(local);
    }

    /**
     * 获取值
     *
     * @param tag 场景
     * @return {@link Object }
     * @author YangXiaoLong
     * @date 2022/11/3 23:29
     */
    public static Object get(String tag) {
        Map<String, Object> val = SYS_THREAD_LOCAL.get();
        if (val == null) {
            return null;
        }
        return val.get(tag);
    }

    /**
     * 移除值
     *
     * @param tag 场景
     * @author YangXiaoLong
     * @date 2022/11/3 23:32
     */
    public static void remove(String tag) {
        Map<String, Object> val = SYS_THREAD_LOCAL.get();
        if (val == null) {
            return;
        }
        val.remove(tag);
        if (val.size() == 0) {
            SYS_THREAD_LOCAL.remove();
        }
    }

    /**
     * 移除所有的值
     *
     * @author YangXiaoLong
     * @date 2022/11/3 23:32
     */

    public static void removeAll() {
        SYS_THREAD_LOCAL.remove();
    }

    /**
     * 场景常量
     *
     * @author YangXiaoLong
     * @date 2022/11/3 23:34
     */
    public static class Tag {
        /**
         * 权限
         */
        public static final String TOKEN = "token";
        /**
         * 灰度发布
         */
        public static final String GRAY = "gray";
    }
}
